import React, { Component, useRef, useEffect } from 'react'
/**
 *
 * <Image width={100} height={200} lazy src="1.png" />
 */

// io.observe(document.querySelector('img'))  开始观察，接受一个DOM节点对象
// io.unobserve(element)   停止观察 接受一个element元素
// io.disconnect() 关闭观察器

function loadImageAsync(url) {
  return new Promise(function (resolve, reject) {
    const image = new Image()
    image.onload = function () {
      setTimeout(() => {
        resolve(true)
      }, 3000)
    }
    image.onerror = function () {
      reject(false)
    }

    image.src = url
  })
}

const ImageView = (props) => {
  const imgRef = useRef(null)
  const { loadSrc, src, lazy, width, height, alt } = props
  useEffect(() => {
    const callback = async (entries) => {
      for (let img of entries) {
        console.log(img, 'img----------->')
        if (img.isIntersecting) {
          try {
            // 2. 开始加载图片，
            let src = img.target.dataset.src
            console.log('src:', src)
            let response = await loadImageAsync(src)
            console.log('response:', response)
            if (response) {
              img.target.setAttribute('src', src)
            }
          } catch (err) {
            // 捕捉失败图片
            img.target = '1.png'
          }
        }
      }
    }
    // 1. 监听图片是否进入滚动区域
    const io = new IntersectionObserver(callback)

    if (imgRef.current) {
      io.observe(imgRef.current)
    }
  }, [])

  return (
    <div>
      <img ref={imgRef} src={loadSrc} data-src={src} alt="" />
    </div>
  )
}

ImageView.defaultProps = {
  loadSrc: '/geren.png',
}

export default ImageView
